use wasm_bindgen::prelude::*;
use image::{DynamicImage, ImageFormat, ImageOutputFormat};
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;


#[wasm_bindgen]
pub struct ImageHandle {
  raw_image: DynamicImage,
  raw_format: ImageOutputFormat,
}

#[wasm_bindgen]
impl ImageHandle {
  // 从buffer中载入图片
  pub fn load_from_memory(&mut self, buffer: Vec<u8>, format: &str ) {
    self.raw_image = image::load_from_memory(&buffer).unwrap();
    let raw_format = ImageFormat::from_extension(format.to_ascii_lowercase()).unwrap();
    self.raw_format = ImageOutputFormat::from(raw_format);
  }
  // 裁剪
  pub fn crop(&self, x: u32, y: u32, width: u32, height: u32)->Vec<u8>{
    let sub_img = DynamicImage::crop_imm(&self.raw_image,x,y,width,height);
    let mut bytes:Vec<u8> = Vec::new();
    sub_img.write_to(&mut bytes,image::ImageOutputFormat::Png).unwrap();
    bytes
  }
}